<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/9/12
 * Time: 下午3:19
 */

namespace Admin\Ims\Controllers;


use Admin\Models\ims\XHImsBoxIn;
use Admin\Models\ims\XHImsBoxOut;
use Admin\Models\ims\XHImsProdIn;
use Admin\Models\ims\XHImsProdOut;
use Admin\Models\ims\XHImsProdType;
use Admin\Models\ims\XHImsProduct;
use Admin\Models\ims\XHImsReceive;
use Admin\Models\ims\XHImsReturn;
use Admin\Models\ims\XHsysDeviceStore;
use Admin\Models\crm\XhcustInfo;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\sys\XhsysEnum;
use Couchbase\UserSettings;
use Helpers\Assets;
use Helpers\Hrm;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\XhException;
use Modules\Ims;
use Phalcon\Exception;

class ResController extends ControllerBase
{

    public function extraPower($tag){
        if(User::isAdmin()){
            return true;
        }
        $deps = User::getExtraPower('dep',$tag);
        $userIds = Hrm::getUserByDepId($deps);
        $newArr = [];
        foreach ($userIds as $ids){
            $newArr =array_merge($newArr,$ids);
        }
        $newArr = array_values(array_filter($newArr));

        return $newArr;
    }


    public function isSingle($name){
        $single  = ['个','只','张','瓶','支','台','包'];
        $total   = ['箱','袋','盒','条'];
        if(in_array($name,$total)){
            return false;
        }
        if(in_array($name,$single)){
            return true;
        }
    }


    private static $enums = [
        'boxInState'  => [1=>'正常',2=>'已出库',3=>'开箱',4=>'清空'],
        'prodInState' => [1=>'正常',2=>'已出库',3=>'出库录入'],
        'boxOutType'  => [1=>'整箱',2=>'部分'],
        'prodOutType' => [1=>'单设备',2=>'整箱'],
    ];

    public function indexAction(){
        echo 'res';
    }

    public function notFoundAction()
    {
        return $this->response->setStatusCode(404)->setJsonContent(['error' => 'Page Not Found']);
    }

    /**
     * 库存信息列表
     * created by dale 2017/9/26
     */
    public function ResListAction(){
        UserPower::checkUserPower('Ims_ResList') or die('缺少权限');
        Assets::easyUI();
        Assets::importJs('js/res/resList.js');
//        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/myTool.js');
        $this->view->pick('res/resList');
        Template::exists('resList', 'list') or die(Main::showMessageModal('resList配置文件不存在，请先创建！', 109106002));
        $listSearchArr = $listButtonArr = [];
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');

        $this->view->setVars(array(
            'resList' => Template::createList('resList', 'resList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, false),
//                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ]),
        ));
    }

    /**
     * 获取库存信息
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/9/26
     */
    public function getResAction(){
        $params = [
            'columns'=>'iProdId,iTypeId,sProdName',
            'conditions'=>'bDelete=0',
            'order'=>'iTypeId',
        ];

        $data = Main::runModelPaginator('Admin\Models\ims\XHImsProduct',$params,true);
        $boxs=XHImsBoxIn::find([
            'columns'   =>'iBoxId,iProdId,iTypeId,iProdNum,iLeftNum,iState',
            'conditions' => 'bDelete=0',
            'order'=>'iProdId'
        ])->toArray();
        $prods=XHImsProdIn::find([
            'columns'   =>'iPInId,iProdId,iTypeId,iBoxId,iState',
            'conditions'=>'bDelete=0 and iBoxId is null',
            'order'=>'iProdId'
        ])->toArray();

        $outBox = XHImsBoxOut::find([
            'columns'   =>'iBOutId,iProdId,iTypeId,iOutNum',
            'conditions' => 'bDelete=0',
            'order'=>'iProdId'
        ])->toArray();

        $outProd = XHImsProdOut::find([
            'columns'   =>'iPOutId,iProdId,iTypeId,iBoxId',
            'conditions' => 'bDelete=0 and iBoxId is null',
            'order'=>'iProdId'
        ])->toArray();

        $newBox=[];
        foreach ($boxs as $val){
            $newBox[$val['iProdId']][]=$val;
        }
        $newProd=[];
        foreach ($prods as $val){
            $newProd[$val['iProdId']][]=$val;
        }

        $newBoxOut = [];
        foreach ( $outBox as $val ){
            $newBoxOut[$val['iProdId']][]=$val;
        }
        $newProdOut=[];
        foreach ($outProd as $val){
            $newProdOut[$val['iProdId']][]=$val;
        }


        $types=XHImsProdType::getProdTypeEnum();
        foreach ($data['rows'] as $index=>$row){
            $totalNum=0;//总数量
            $outNum = 0;//出库数量
            if(isset($newBox[$row['iProdId']])){
                foreach ($newBox[$row['iProdId']] as $value){
                    $totalNum += $value['iProdNum'];
                }
            }
            if(isset($newProd[$row['iProdId']])){
                $totalNum += count($newProd[$row['iProdId']]);
            }

            if(isset($newBoxOut[$row['iProdId']])){
                foreach ($newBoxOut[$row['iProdId']] as $value){
                    $outNum += $value['iOutNum'];
                }
            }
            if(isset($newProdOut[$row['iProdId']])) {
                $outNum += count($newProdOut[$row['iProdId']]);
            }

            $data['rows'][$index]['totalNum'] = $totalNum;
            $data['rows'][$index]['leftNum']  = $totalNum - $outNum;
            $data['rows'][$index]['typeName'] = $types[$row['iTypeId']];



//            if($row['iPrice']){
//                $data['rows'][$index]['totalPrice'] = $row['iPrice'] *  $leftNum;
//            }else{
//                $data['rows'][$index]['totalPrice'] = 0;
//            }

        }

        return $this->sendJsonResponse($data);
    }

    public function resInFormAction(){
        Assets::easyUIMobile();
        $this->view->pick('res/resInForm');
        Assets::importJs('js/res/resInForm.js');
        $types=XHImsProdType::find([
            'columns'=>'iTypeId,sTypeName',
            'conditions'=>'bDelete=0',
        ]);
        $types=array_column($types->toArray(),'sTypeName','iTypeId');
        $this->view->setVars([
            'types'=>$types,
        ]);
    }


    /**
     * 出入明细
     * created by dale 2017/9/27
     */
    public function resDetailAction(){
        UserPower::checkUserPower('Ims_ResInList') or die('缺少权限');
        Assets::easyUI();
        Assets::importJs('js/res/resDetail.js');
        Assets::importJs('js/myTool.js');
        $this->view->pick('res/resDetail');
        Template::exists('resInList', 'list') or die(Main::showMessageModal('boxInList配置文件不存在，请先创建！', 109106002));
        Template::exists('resOutList', 'list') or die(Main::showMessageModal('prodInList配置文件不存在，请先创建！', 109106002));
        $listSearchArr1 = $listSearchArr2 = [];
        $listSearchArr1[] = array('type' => 'text', 'id' => 'resIn_search', 'label' => ' 搜索： ');
        $listSearchArr1[] = array('type' => 'button', 'id' => 'bt_resIn_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');

        $listSearchArr2[] = array('type' => 'text', 'id' => 'resOut_search', 'label' => ' 搜索： ');
        $listSearchArr2[] = array('type' => 'button', 'id' => 'bt_resOut_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $this->view->setVars(array(
            'resInList' => Template::createList('resInList', 'resInList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr1, false),
            ]),
            'resOutList' => Template::createList('resOutList', 'resOutList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr2, false),
            ]),
        ));
    }



    /**
     * 入库明细
     *
     * created by dale 2017/9/28
     */
    public function resOutListAction(){
        UserPower::checkUserPower('Ims_ResOutList') or die('缺少权限');
        Assets::easyUI();
        Assets::importJs('js/res/resOutList.js');
        Assets::importJs('js/myTool.js');
        $this->view->pick('res/resOutList');
        Template::exists('resOutList', 'list') or die(Main::showMessageModal('boxOutList配置文件不存在，请先创建！', 109106002));
        $listSearchArr1 = $listSearchArr2 = [];
        $listSearchArr1[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr1[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        if(UserPower::checkUserPower('Ims_ResOutList_Add')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_addTab', 'text' => '出库', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('Ims_ResOutList_Edit')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_editPrice', 'text' => '编辑价格', 'icon' => 'fa-edit');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_addDesc', 'text' => '添加备注', 'icon' => 'fa-edit');
        }
        if(UserPower::checkUserPower('Ims_ResOutList_Del')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $this->view->setVars(array(
            'resOutList' => Template::createList('resOutList', 'resOutList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr1, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ])
        ));
    }

    /**
     * 出库明细数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * created by dale 2017/9/28
     */
    public function getResOutAction($showAll=false){
        $this->view->disable();
//        $page     = $this->request->getPost('page', 'int', 1);                     //获取页码，默认1
//        $rows     = $this->request->getPost('rows', 'int', 0);                     //获取行数，默认0行
//        $offset   = $rows * ($page - 1);

        $key   = $this->request->getPost('key','string');
        $order = $this->request->getPost('order','string');
        $sort  = $this->request->getPost('sort','string');
        $iProdId = $this->request->getPost('id','string');

        try {
            $sql = " SELECT iBOutId as id,'box' as flag,iProdId,iTypeId,NULL as sProdCode,iOutPrice,iBoxId,iOutNum,iType,iSchoolId,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId,sYear,iChargeMode,bDelete,sRemark,iLRId FROM XHIms_BoxOut   
                    UNION ALL   
                    SELECT iPOutId as id,'prod' as flag,iProdId,iTypeId,sProdCode,iOutPrice,iBoxId,1,iType,iSchoolId,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId,sYear,iChargeMode,bDelete,null as sRemark,iLRId FROM XHIms_ProdOut WHERE iBoxId is  NULL ";
            $sql = "select t.*,i.sSchoolName,p.sProdName,pt.sTypeName from ({$sql}) as t LEFT JOIN XHCust_Info as i ON i.iSchoolId=t.iSchoolId  LEFT JOIN XHIms_Product as p ON p.iProdId=t.iProdId LEFT JOIN XHIms_ProdType as pt ON pt.iTypeId=t.iTypeId WHERE t.bDelete = 0  ";
            if($key){
               $sql.=" and ( i.sSchoolName like '%".$key."%' OR p.sProdName like '%".$key."%' OR pt.sTypeName like '%".$key."%') ";
            }
            if($iProdId){
                if($key){
                    $sql.="AND t.iProdId=".$iProdId." ";
                }else{
                    $sql.="and t.iProdId=".$iProdId." ";
                }
            }

            if(!User::isAdmin() && !$showAll ){ //不是超管
                $nowUserId = Main::getLoginUserInfo('userId');
                if(User::getExtraPower('dep','resOut',$nowUserId,true)){ //有额外权限
                    $userIds = $this->extraPower('resOut');
                    $sql .= "AND ( t.iCreateUserId  in ( ".implode(',',$userIds)." ) OR t.iCreateUserId = {$nowUserId} ) ";
                }else{
                    $sql .= "AND  t.iCreateUserId = {$nowUserId}  ";
                }
            }

            if($order&&$sort){
                if($sort=='sProdName'){
                    $sql.="ORDER BY p.sProdName ".$order;
                }else if($sort=='sTypeName'){
                    $sql.="ORDER BY pt.sTypeName ".$order;
                }else if($sort=='sSchoolName'){
                    $sql.="ORDER BY i.sSchoolName ".$order;
                }else{
                    $sql.="ORDER BY t.".$sort." ".$order;
                }
            }else{
               $sql.="ORDER BY t.tCreateDate desc , t.id asc ";
            }
            $data = Main::runSqlPage(['query'=>"select :columns: from ({$sql}) as t",'columns'=>'t.*']);
            $enums = self::$enums;
            $footer = [];
            $footer['sBoxCode'] = '总计:';
            $footer['iOutNum'] = 0; //出库数目
            $enums['iChargeMode'] = XhsysEnum::getEnumByNodeName('收费模式');
            $receiveIds = array_values(array_unique(array_filter(array_column($data['rows'] , 'iLRId'))));
            $receiveUsers = $this->getReceiveUser($receiveIds);
            foreach ($data['rows'] as $index => &$rows){
                $rows['keyId'] = $rows['flag'] . '-' . $rows['id'];
                if(isset($rows['iChargeMode'])) {
                    $rows['iChargeMode'] = $enums['iChargeMode'][$rows['iChargeMode']];
                }
                if($rows['flag']=='box'){
                    $footer['iOutNum'] += $rows['iOutNum'];
                    $rows['iType'] = $enums['boxOutType'][$rows['iType']];
                }else{
                    $footer['iOutNum'] += 1;
                    $rows['iType'] = $enums['prodOutType'][$rows['iType']];
                }
                $iLRId = Tool::getValue($rows , 'iLRId' , null);
                if ($iLRId) {
                    $rows['infoIcon']='<i class="fa fa-dropbox"  style="color:grey;" title="领用出库，id:'.$iLRId.'"></i>';
                    $rows['sReceiveUser'] = isset($receiveUsers[$iLRId]) ? $receiveUsers[$iLRId] : '';
                }
            }
            $footer['sProdName'] = '销售总额：'. $this->calculatePrice($data['rows'] , 'iOutPrice','iOutNum');
            Main::runUserNameById($data['rows'] , ['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'],true);
            return $this->sendJsonResponse($data);
        }catch (\Exception $e){
           return $this->sendErrorResponse(500 ,$e->getMessage());
        }
    }


    public function getReceiveUser($receiveIds){
        if(count($receiveIds) <= 0){
            return [];
        }
        $receives = XHImsReceive::find([
            'columns'    => 'iLRId,iReceiveId',
            'conditions' => 'bDelete = 0 and iLRId in ({ids:array})',
            'bind'       => ['ids' => $receiveIds]
        ])->toArray();
        Main::runUserNameById($receives , ['iReceiveId' => 'sReceiveUser'], true);
        return array_column($receives , 'sReceiveUser' ,'iLRId');
    }

    /**
     * 设备出库表单
     *
     * created by dale 20171130
     */
    public function devOutFormAction(){
        Assets::easyUIMobile();
        $this->view->pick('res/devOutForm');
        Assets::select2();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/res/devOutForm.js');

        $schools = XhcustInfo::find([
            'columns' => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete=0 AND iSchoolId is not null'
        ]);
        $schools = array_column($schools->toArray(), 'sSchoolName', 'iSchoolId');
        $sYear = [];
        $year = intval(date('Y', time()));
        for ($i = 0; $i < 6; $i++) {
            $sYear[$year] = $year;
            $year--;
        }
        $this->view->setVars([
            'schools' => $schools,
            'iChargeMode' => XhsysEnum::getEnumByNodeName('收费模式'),
            'sYear' => $sYear
        ]);
    }

    public function otherOutFormAction(){
        Assets::easyUIMobile();
        $this->view->pick('res/otherOutForm');
        Assets::importJs('js/res/otherOutForm.js');

        $schools = XhcustInfo::find([
            'columns' => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete=0 AND iSchoolId is not null'
        ]);
        $schools = array_column($schools->toArray(), 'sSchoolName', 'iSchoolId');
        $sYear = [];
        $year = intval(date('Y', time()));
        for ($i = 0; $i < 6; $i++) {
            $sYear[$year] = $year;
            $year--;
        }
        $this->view->setVars([
            'schools' => $schools,
            'iChargeMode' => XhsysEnum::getEnumByNodeName('收费模式'),
            'sYear' => $sYear
        ]);
    }



    public function ResInListAction(){
        UserPower::checkUserPower('Ims_ResInList') or die('没有权限');
        Assets::easyUI();
        Assets::importJs('js/res/resInList.js');
        Assets::importJs('js/myTool.js');
        $this->view->pick('res/resInList');
        Template::exists('resInList', 'list') or die(Main::showMessageModal('resInList配置文件不存在，请先创建！', 109106002));
        $listSearchArr1 = $listButtonArr = [];
        $listSearchArr1[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr1[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        if(UserPower::checkUserPower('Ims_ResInList_Add')){
//            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_addScan', 'text' => '扫码入库', 'icon' => 'fa-plus');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '入库', 'icon' => 'fa-plus');
        }
        if (UserPower::checkUserPower('Ims_ResInList_Edit')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_editPrice', 'text' => '编辑价格', 'icon' => 'fa-edit');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_addDesc', 'text' => '添加备注', 'icon' => 'fa-edit');
        }
        if(UserPower::checkUserPower('Ims_ResInList_Del')){
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $this->view->setVars(array(
            'resInList' => Template::createList('resInList', 'resInList', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr1, true),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
            ])
        ));
    }

    public function getResInAction($showAll=false){
        $this->view->disable();
        $page     = $this->request->getPost('page', 'int', 1);                     //获取页码，默认1
        $rows     = $this->request->getPost('rows', 'int', 0);                     //获取行数，默认0行
        $offset   = $rows * ($page - 1);

        $key   = $this->request->getPost('key','string');
        $order = $this->request->getPost('order','string');
        $sort  = $this->request->getPost('sort','string');
        $iProdId = $this->request->getPost('id','string');

        try {
            $sql = " SELECT iBoxId as id,'box' as flag,iProdId,iTypeId,sBoxCode as code,iInPrice,NULL as iBoxId,iProdNum,iLeftNum,iState,sRemark,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId,bDelete,iLRTId FROM XHIms_BoxIn   UNION ALL 
                    SELECT iPInId as id,'prod' as flag,iProdId,iTypeId,sProdCode as code,iInPrice,iBoxId,NULL ,NULL ,iState,sRemark,tCreateDate,iCreateUserId,tLastModifyDate,iLastModifyUserId,bDelete,iLRTId FROM XHIms_ProdIn WHERE iBoxId  is NULL ";
            $sql = "select t.*,p.sProdName,pt.sTypeName from ({$sql}) as t  LEFT JOIN XHIms_Product as p ON p.iProdId=t.iProdId LEFT JOIN XHIms_ProdType as pt ON pt.iTypeId=t.iTypeId where t.bDelete = 0 ";

            if($key){
                $sql.=" AND (t.code like '%".$key."%' OR p.sProdName like '%".$key."%' OR pt.sTypeName like '%".$key."%') ";
            }
            if($iProdId){
                if($key){
                    $sql.="AND t.iProdId=".$iProdId."  ";
                }else{
                    $sql.="AND t.iProdId=".$iProdId." ";
                }
            }

            if(!User::isAdmin() && !$showAll){ //不是超管
                $nowUserId = Main::getLoginUserInfo('userId');
                if(User::getExtraPower('dep','resIn',$nowUserId,true)){ //有额外权限
                    $userIds = $this->extraPower('resIn');

                    $sql .= "AND ( t.iCreateUserId  in ( ".implode(',',$userIds)." ) OR t.iCreateUserId = {$nowUserId} ) ";
                }else{
                    $sql .= "AND  t.iCreateUserId = {$nowUserId}  ";
                }
            }


            if($order&&$sort){
                if($sort=='sProdName'){
                    $sql.="ORDER BY p.sProdName ".$order;
                }else if($sort=='sTypeName'){
                    $sql.="ORDER BY pt.sTypeName ".$order;
                }else{
                    $sql.="ORDER BY t.".$sort." ".$order;
                }
            }else{
                $sql.="ORDER BY t.tCreateDate desc , t.id asc ";
            }

            $query = "select count(*) as count from ({$sql}) as t";
            $total = $this->db->fetchOne($query);
            $total = $total['count'];
            $sql  .= " LIMIT {$offset},{$rows}";
            $data  = $this->db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
        }catch (\Exception $e){
            echo $e->getMessage();die();
        }
        $enums = self::$enums;
        $footer = [];
        $footer['sProdName'] = '总计:';
        $footer['iProdNum'] = 0; //总数
        $footer['iLeftNum'] = 0;      //剩余数目
        $returnIds = array_values(array_unique(array_filter(array_column($data , 'iLRTId'))));
        $returnUsers = $this->getReturnUser($returnIds);
        foreach ($data as $index=>$rows){
            $data[$index]['keyId'] = $rows['flag'].'-'.$rows['id'];
            if($rows['flag']=='box'){  //箱盒
                $footer['iProdNum'] += $rows['iProdNum'];
                $footer['iLeftNum'] += $rows['iLeftNum'];
                $data[$index]['iState'] = $enums['boxInState'][$rows['iState']];
//                if($rows['iState']==1){
//                    $data[$index]['infoIcon'] = '<i class="fa fa-inbox"  style="color:#0033cc;"></i>';
//                }else{
//                    $data[$index]['infoIcon'] = '<i class="fa fa-dropbox"  style="color:grey;"></i>';
//                }
            }else{
                $data[$index]['iState'] = $enums['prodInState'][$rows['iState']];
                $data[$index]['iProdNum'] = 1;
//                if($rows['iState']==1){
//                    $data[$index]['iLeftNum'] = 1;
//                    $data[$index]['infoIcon'] = '<i class="fa fa-tablet"  style="color:#0033cc;"></i>';
//                }else{
//                    $data[$index]['iLeftNum'] = 0;
//                    $data[$index]['infoIcon'] = '<i class="fa fa-tablet"  style="color:grey;"></i>';
//                }
                if($data[$index]['iBoxId'] == null){
                    $footer['iProdNum'] += 1; //总数
                    $footer['iLeftNum'] += $data[$index]['iLeftNum'];
                }else{
                    $footer['iProdNum'] += 0;
                }
            }
            $iLRTId = Tool::getValue($rows,'iLRTId' , null);
            if ($iLRTId){
                $data[$index]['infoIcon']    = '<i class="fa fa-inbox"  style="color:#0033cc;" title="归还入库,id:'.$iLRTId.'"></i>';
                $data[$index]['sReturnUser'] = isset($returnUsers[$iLRTId]) ? $returnUsers[$iLRTId] : '';
            }

        }
        $footer['sTypeName'] = '采购总价:' . $this->calculatePrice($data , 'iInPrice');

        Main::runUserNameById($data,['iCreateUserId'=>'iCreateUserId','iLastModifyUserId'=>'iLastModifyUserId'],true);
        return $this->sendJsonResponse(['total'=>$total,'rows'=>$data,'footer'=>array($footer)]);
    }

    /**
     * 获取归还的人
     *
     * @param $returnIds
     * @return array
     *
     * create by xjq 20180626
     */
    public function getReturnUser($returnIds){
        if(count($returnIds) <= 0){
            return [];
        }
        $returns = XHImsReturn::find([
            'columns'    => 'iLRTId,iReturnId',
            'conditions' => 'bDelete = 0 and iLRTId in ({ids:array})',
            'bind'       => ['ids' => $returnIds]
        ])->toArray();
        Main::runUserNameById($returns , ['iReturnId' => 'sReturnUser'], true);
        return array_column($returns , 'sReturnUser' ,'iLRTId');
    }


    public function getTypeOtherAction($singleTab = false){
        $types = XHImsProdType::getProdTypeEnum();
        $arr = [];
        if($singleTab){//只要平板
            foreach ($types as $index=>$value){
                if($value == '平板'){
                    $arr[]=['id'=>$index,'text'=>$value];
                }
            }
        }else{
            foreach ($types as $index=>$value){
                if($value != '平板'){
                    $arr[]=['id'=>$index,'text'=>$value];
                }
            }
        }
        return json_encode($arr);
    }


    /**
     * 箱子内的货物
     *
     * created by dale 2017929
     */
    public function prodsInBoxAction(){
        Assets::easyUI();
        Assets::importJs('js/res/prodsInBox.js');
        Assets::importJs('js/myTool.js');
        $this->view->pick('res/prodsInBox');
        Template::exists('prodsInBox', 'list') or die(Main::showMessageModal('prodsInBox配置文件不存在，请先创建！', 109106002));
        $listSearchArr1 = $listSearchArr2 = [];
        $listSearchArr1[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr1[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search', 'style' => 'margin-left:10px');
        $this->view->setVars(array(
            'prodsInBox' => Template::createList('prodsInBox', 'prodsInBox', [
//                'searchToolbar' => Template::createSearchToolBar($listSearchArr1, false),
            ])
        ));
    }

    /**
     * 获取盒子内的货物
     *
     * created by dale 2017929
     */
    public function getProdByBoxAction(){
        $this->view->disable();
        $iBoxId = $this->request->getPost('iBoxId') or die('缺少参数');
        $page     = $this->request->getPost('page', 'int', 1);                     //获取页码，默认1
        $rows     = $this->request->getPost('rows', 'int', 0);                     //获取行数，默认0行
        $offset   = $rows * ($page - 1);

        try {
            $sql = " SELECT iPInId as id,'in' as flag,iProdId,iTypeId,sProdCode,iBoxId,iState,sRemark,tCreateDate,iCreateUserId FROM XHIms_ProdIn WHERE bDelete=0 AND iState=1  UNION ALL SELECT iPOutId as id,'out' as flag,iProdId,iTypeId,sProdCode,iBoxId,iType,NULL ,tCreateDate,iCreateUserId   FROM XHIms_ProdOut WHERE bDelete=0 ";
            $sql = "select t.*,p.sProdName,pt.sTypeName from ({$sql}) as t  LEFT JOIN XHIms_Product as p ON p.iProdId=t.iProdId LEFT JOIN XHIms_ProdType as pt ON pt.iTypeId=t.iTypeId WHERE t.iBoxId=".$iBoxId;

//            if($key){
//                $sql.=" AND (t.code like '%".$key."%' OR p.sProdName like '%".$key."%' OR pt.sTypeName like '%".$key."%') ";
//            }
            $query = "select count(*) as count from ({$sql}) as t";
            $total = $this->db->fetchOne($query);
            $total = $total['count'];
            $sql  .= " LIMIT {$offset},{$rows}";
            $data  = $this->db->query($sql)->fetchAll(\PDO::FETCH_ASSOC);
        }catch (\Exception $e){
            echo $e->getMessage();die();
        }

        foreach ($data as $index=>$rows){
            $data[$index]['keyId'] = $rows['flag'].'-'.$rows['id'];
            if($rows['flag']=='in'){
                $data[$index]['infoIcon'] = '<i class="fa fa-tablet"  style="color:#0033cc;"></i>';
            }else{
                $data[$index]['infoIcon'] = '<i class="fa fa-tablet"  style="color:grey;"></i>';
            }
        }


        return $this->sendJsonResponse(['total'=>$total,'rows'=>$data]);

    }

    /**
     * 删除入库信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * created by dale 20171130
     */
    public function DelInAction(){
        $flag = $this->request->getPost('flag', 'string');
        $id   = $this->request->getPost('id', 'string');

        if($flag == 'prod'){
            $obj = XHImsProdIn::findFirst($id);
        }else{
            $obj = XHImsBoxIn::findFirst($id);
        }

        if(Main::getLoginUserInfo('logonName') != 'admin'){ //权限控制
            if(UserPower::checkUserPower('Ims_ResInList_Del')
                && $obj->iCreateUserId == Main::getLoginUserInfo('userId')){
                $check = true;
            }else{
                $check = false;
            }
        }else {
            $check = true;
        }

        if(!$check){
            return $this->sendJsonResponse(400,'没有权限');
        }
        if ($obj->iLRTId){
            return $this->sendErrorResponse(500 , '归还关联记录无法删除');
        }
        $obj->bDelete = 1;
        $res = $obj->save();
        if($res){
            return $this->sendSuccessResponse('删除成功,已过滤无法删除的记录');
        }else{
            return $this->sendErrorResponse(500, '删除失败');
        }
    }



    public function delOutAction(){
        $flag = $this->request->getPost('flag', 'string');
        $id   = $this->request->getPost('id', 'string');

        if($flag == 'prod'){
            $obj = XHImsProdOut::findFirst($id);
        }else{
            $obj = XHImsBoxOut::findFirst($id);
        }

        if(Main::getLoginUserInfo('logonName') != 'admin'){ //权限控制
            if(UserPower::checkUserPower('Ims_ResOutList_Del')
                && $obj->iCreateUserId == Main::getLoginUserInfo('userId')){
                $check = true;
            }else{
                $check = false;
            }
        }else {
            $check = true;
        }

        if(!$check){
            return $this->sendJsonResponse(400,'没有权限');
        }
        if($obj->iLRId) {
            return $this->sendErrorResponse(500 ,'领用申领关联记录无法直接删除');
        }
        $obj->bDelete = 1;
        $res = $obj->save();
        if($res){
            return $this->sendSuccessResponse('删除成功，已过滤无法删除的记录');
        }else{
            return $this->sendErrorResponse(500, '删除失败');
        }
    }


    public function getProdTypeAction(){
        return json_encode(XHImsProdType::getProdTypeEnum());
    }

    /**
     * 获取价格
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180424
     */
    public function getPriceAction(){
        $prodId = $this->request->getPost('prodId', 'int');
        $type   = $this->request->getPost('type', 'string');
        if ( !$prodId  || !$type ) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $obj = XHImsProduct::findFirst($prodId);
        if ( !$obj ) {
            return $this->sendErrorResponse(400,'未找到商品');
        }
        if ($type == 'in'){
            return $this->sendJsonResponse(['price' => $obj->iInPrice ?: 0 ]);
        }else if($type == 'out'){
            return $this->sendJsonResponse(['price' => $obj->iOutPrice ?: 0 ]);
        }else {
            return $this->sendErrorResponse(500 , '类型不匹配' );
        }

    }



    public function getSYearModeAction(){

        $sYear = [];
        $year = intval(date('Y', time()));
        for ($i = 0; $i < 6; $i++) {
            $sYear[$year] = $year;
            $year--;
        }

        $schools = XhschoolInfo::find([
            'columns' => 'iSchoolId,sSchoolName',
            'conditions' => 'bDelete=0 AND iSchoolId is not null AND ( iStatus = 2 OR iStatus = 3 )',
        ]);
        $schools  = array_column($schools->toArray(), 'sSchoolName', 'iSchoolId');
        $chargeMode = XhsysEnum::getEnumByNodeName('收费模式');
        $arr = [
            'schools'    => $schools,
            'chargeMode' => $chargeMode,
            'sYear'      => $sYear,
        ];
        return $this->sendJsonResponse($arr);
    }

    public function getProdAction(){
        $iTypeId = $this->request->getPost('id');
        if(!$iTypeId){
            return $this->sendErrorResponse(500, '缺少参数');
        }
        $objs = XHImsProduct::find([
            'columns'    => 'iProdId,sProdName',
            'conditions' => 'bDelete = 0 AND iTypeId =:iTypeId:',
            'bind'       => ['iTypeId' => $iTypeId ],
        ])->toArray();
        return json_encode(array_column($objs,'sProdName','iProdId'));
    }

    /**
     * 获取到其他数目的数量
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * created by dale 2017124
     */
    public function getOtherNumAction(){
        $prodId = $this->request->getPost('prodId');
        if(!$prodId){
            return $this->sendErrorResponse(500, '缺少参数');
        }
        $objs = XHImsBoxIn::find([
            'conditions' => 'bDelete =0 AND iProdId = :iProdId: AND iState = 1',
            'bind'       => ['iProdId' => $prodId],
        ]);
        $leftNum = 0;
        if($objs->toArray()!=[]){
            foreach ($objs as $obj){
                $leftNum += $obj->iLeftNum;
            }
        }
        return json_encode(['leftNum'=>$leftNum]);
    }



    /**
     * 获取出库信息,
     *
     * create by dale 20171212
     */
    public function getOutNumAction($schoolId){
        $year = intval(date('Y', time()));
        for ($i = 0; $i < 6; $i++) {
            $sYear[$year] = $year;
            $year--;
        }
        if (!$schoolId ){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $now = date('Y-m-d',time());
        $sql = "select sYear,iOutNum from XHIms_BoxOut WHERE DATE_FORMAT(tCreateDate,'%Y-%m-%d') = '{$now}' AND iSchoolId = '{$schoolId}' AND bDelete = 0  ORDER BY sYear";
        $data = $this->db->fetchAll($sql);
        $total = 0;
        $newArr = [];
        if (count($data) != 0){
            foreach ($data as $index=>$value){
                $total += $value['iOutNum'];
                if(isset($newArr[$value['sYear']])){
                    $newArr[$value['sYear']] += $value['iOutNum'];
                }else{
                    $newArr[$value['sYear']] = 0;
                    $newArr[$value['sYear']] += $value['iOutNum'];
                }
            }
        }

        $sql  = "select sYear from XHIms_ProdOut WHERE DATE_FORMAT(tCreateDate,'%Y-%m-%d') = '{$now}' AND iSchoolId = '{$schoolId}' AND bDelete = 0  ORDER BY sYear";
        $data = $this->db->fetchAll($sql);

        $total += count($data);
        if (count($data) != 0){
            foreach ($data as $index=>$value){
                if(isset($newArr[$value['sYear']])){
                    $newArr[$value['sYear']] += 1;
                }else{
                    $newArr[$value['sYear']] = 0;
                    $newArr[$value['sYear']] += 1;
                }
            }
        }
        $schoolName = XhschoolInfo::getSchoolArray()[$schoolId];
        $content    = '<table class="table table-hover"><tr class="info"><td>学校:</td><td>'.$schoolName.'</td></tr>';
        foreach ($newArr as $index=>$value){
            if($index == ''){
                $content .= '<tr><td>未知:</td><td>'.$value.'</td></tr>';
            }else{
                $content .= '<tr><td>'.$index.':</td><td>'.$value.'</td></tr>';
            }

        }
        $content .='<tr><td>合计:</td><td>'.$total.'</td></tr></table>';
        return $content;
    }



    /**
     * 设备出库
     *
     * created by dale 2017126
     */
    public function saveOutTabAction()
    {
        $sMeasure = $this->request->getPost('sMeasure', 'string', '只');
        $code = $this->request->getPost('code', 'string');
        $resultStr = '';
        $postData  = $this->request->getPost();
        $dateTime = date('Y-m-d',time());
        if ($sMeasure == '箱') { //注意箱出库时要把属于箱子的所有平板出库。
            $outBox = new XHImsBoxOut();
            $box = XHImsBoxIn::findFirst([
                'conditions' => 'sBoxCode = :code: AND iState = :iState: AND bDelete = 0',
                'bind' => ['code' => $code, 'iState' => 1],
            ]);
            if (!$box){
                return $this->sendErrorResponse(500,'箱子不存在或已出库');
            }
            //处理出库记录
            $outBox->assign($postData);
            $outBox->iOutNum = $box->iLeftNum;
            $outBox->iBoxId  = $box->iBoxId;

            $resultStr = $dateTime ."箱子".$box->sBoxCode."出库".$box->iLeftNum;
            $box->sRemark  = $dateTime ."出库".$box->iLeftNum;
            $box->iLeftNum = 0;
            $box->iState   = 2;
            if($box->save()){ //箱子出库 1.把所有的属于该箱子的商品出库  2.保存出库信息。
                $resultStr .= '成功<br/>';
                $outBox->iType  = 1;//整箱出库
                if ($outBox->save()){
                    $resultStr .= '出库记录,编号：'.$outBox->iBOutId.'保存成功<br/>';
                }else{
                    $resultStr .= '出库记录保存失败<br/>';
                }
                $prods = XHImsProdIn::find([
                    'conditions' => 'iBoxId = :iBoxId: AND iState =:iState:',
                    'bind'       => ['iBoxId' => $box->iBoxId,'iState' => 1]
                ]);
                if(count($prods) != 0){
                    foreach ($prods as $prod){
                        //出库记录
                        $prodOut = new XHImsProdOut();
                        $prodOut->assign($postData);
                        $prodOut->iType = 2; //整箱出库
                        $prodOut->iBoxId = $prod->iBoxId;
                        $prodOut->sProdCode = $prod->sProdCode;

                        $prod->iState  = 2 ;
                        $prod->sRemark = $dateTime.'随箱出库';
                        if($prod->save()){
                            $resultStr .= '物品码:'.$prod->sProdCode.',出库成功<br>';
                            if($prodOut->save()){
                                $resultStr .= '出库记录'.$prodOut->iPOutId.'保存成功';
                            }else{
                                $resultStr .= '出库记录保存失败';
                            }
                        }else{
                            $resultStr .= '箱下物品码:'.$prod->sProdCode.'<span style="color: red">出库失败</span><br>';
                        }
                    }
                }else{
                    $resultStr .= '箱内商品码不存在记录<br>';
                }

            }else{
                $resultStr .= '失败';
            }

        } else {
            $prodIn = XHImsProdIn::findFirst([
                'conditions' => 'sProdCode = :sProdCode:  AND bDelete = 0',
                'bind'       => ['sProdCode' => $code],
            ]);
            if (!$prodIn){ //没有找到记录
                $sBoxCode = $this->request->getPost('sBoxCode','string');
                if(!$sBoxCode){
                    return $this->sendErrorResponse(400,'箱码必填');
                }
                $box = XHImsBoxIn::findFirst([
                    'conditions' => 'sBoxCode = :sBoxCode:AND bDelete = 0',
                    'bind'       => ['sBoxCode'=>$sBoxCode]
                ]);
                if(!$box){
                    return $this->sendErrorResponse(500,'没有找到该箱子，请确认箱码正确');
                }
                if($box->iState == 2){
                    return $this->sendErrorResponse(500,'该箱子已经出库');
                }
                if($box->iProdId != $this->request->getPost('iProdId')){
                    return $this->sendErrorResponse(500,'该箱子里面平板和你选择的平板不是同一个种类');
                }
                $newProd = new XHImsProdIn();
                $newProd->sProdCode = $code;
                $newProd->iProdId = $box->iProdId;
                $newProd->iTypeId = $box->iTypeId;
                $newProd->iBoxId  = $box->iBoxId;
                $newProd->iInPrice = $box->iInPrice;
                $newProd->iState  = 1;
                $newProd->sRemark = $dateTime.'出库前入库';
                if($newProd->save()){
                    $resultStr .='出库前入库成功'.$newProd->iPInId.'<br>';
                    $prodIn = XHImsProdIn::findFirst($newProd->iPInId);
                }else{
                    $resultStr .='出库前入库失败<br>';
                    return $this->sendErrorResponse(500,$resultStr);
                }

            }else{
                if($prodIn->iState ==2){
                    return $this->sendErrorResponse(400,'已出库');
                }
            }

            //出库记录
            $prodOut = new XHImsProdOut();
            $prodOut->assign($postData);
            $prodOut->iBoxId = $prodIn->iBoxId;
            $prodOut->iType  = 1; //单设备出库
            $prodOut->sProdCode = $prodIn->sProdCode;

            $prodIn->iState  = 2;
            $prodIn->sRemark .= $dateTime.'出库1';
            if($prodIn->save()){
                $resultStr .=$dateTime.'出库'.$prodIn->sProdCode.'<br>';
                if($prodIn->iBoxId != null){//箱子保存
                    $box = XHImsBoxIn::findFirst($prodIn->iBoxId);
                    $box->iLeftNum -= 1;
                    if($box->iLeftNum == 0){
                        $box->iState = 2;
                    }
                    if($box->save()){
                        $resultStr .= '箱子'.$box->sBoxCode.'数目减1，剩余：'.$box->iLeftNum.'<br>';
                    }else{
                        $resultStr .= '箱子数目减1保存失败<br>';
                    }
                }
                //出库记录保存
                if($prodOut->save()){
                    $resultStr .= '出库记录'.$prodOut->iPOutId.'保存成功<br>';
                }else{
                    $resultStr .= '出库记录保存失败<br>';
                }

            }else {
                $resultStr .= '出库保存失败<br>';
            }
        }

        $str = $this->getOutNumAction($this->request->getPost('iSchoolId'));

        return $this->response->setJsonContent(['code' => 200, 'msg' => $str], JSON_UNESCAPED_UNICODE);

    }

    /**
     * 其他出库
     *
     * created by dale 2017126
     */
    public function saveOutOtherAction(){
        $iTypeId = $this->request->getPost('iTypeId','int');
        $iProdId = $this->request->getPost('iProdId','int');
        $iLeftNum = $this->request->getPost('iLeftNum','int');
        $iOutNum  = $this->request->getPost('iOutNum','int');
        $iOutPrice = $this->request->getPost('iOutPrice' , 'int');
        if (!$iTypeId || !$iProdId || (!$iOutNum && $iOutNum != 0 ) || !$iLeftNum){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        if($iOutNum > $iLeftNum){
            return $this->sendErrorResponse(400,'出库数量大于剩余数量');
        }
        $nowData = date('Y-m-d',time());
        $resStr = '';
        do{

            $obj = XHImsBoxIn::findFirst([
                'conditions' => 'bDelete = 0 AND iState = 1 AND iProdId =:iProdId:  ',
                'bind'       => ['iProdId' => $iProdId ],
            ]);
            $outObj = new XHImsBoxOut(); //出库记录
            $outObj->iBoxId  = $obj->iBoxId;
            $outObj->iProdId = $obj->iProdId;
            $outObj->iTypeId = $obj->iTypeId;
            $outObj->iType   = 2;
            $outObj->iOutPrice = $iOutPrice;

            if ($obj->iLeftNum - $iOutNum > 0 ){ //剩余数大于出库数
                $outObj->iOutNum = $iOutNum;
                $obj->iLeftNum -= $iOutNum;
                $obj->sRemark .= $nowData . '出库' . $iOutNum . ',';
                $iOutNum = 0;
            }else if($obj->iLeftNum - $iOutNum < 0){ //剩余数小于出库数
                $outObj->iOutNum = $obj->iLeftNum;
                $obj->sRemark .= $nowData . '出库' . $obj->iLeftNum . ',全部出库。';
                $obj->iState   = 2;
                $iOutNum -=  $obj->iLeftNum;
                $obj->iLeftNum = 0;
            }else{  //刚刚好相等
                $outObj->iOutNum = $iOutNum;
                $obj->sRemark .= $nowData . '出库' . $iOutNum . ',全部出库。';
                $iOutNum       = 0;
                $obj->iLeftNum = 0;
                $obj->iState   = 2;
            }
            if($obj->save()){
                $resStr .='库内编号：'.$obj->iBoxId.'操作成功;<br>';
                if($outObj->save()){
                    $resStr .='出库记录：'.$outObj->iBOutId.'保存成功;<br>';
                }else{
                    $resStr .='出库记录保存失败<br>';
                }
            }else{
                $resStr .='库内编号：'.$obj->iBoxId.'操作失败;<br>';
            }
        }while($iOutNum != 0);

        return $this->response->setJsonContent(['code' => 200, 'msg' => $resStr], JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取到盒内的数量
     *
     * created by dale 2017127
     */
    public function getBoxNumAction(){
       $boxCode = $this->request->getPost('boxCode','string');
       if(!$boxCode){
           return $this->sendErrorResponse(400,'缺少参数');
       }
       try{
           $arr = [];
           $sql = "select iBoxId,iProdNum from XHIms_BoxIn where bDelete = 0 AND sBoxCode = '{$boxCode}' ";
           $data = $this->db->fetchAll($sql);
           $arr['total']   = $data[0]['iProdNum'];
           $sql = "select count(iPInId) as nums from XHIms_ProdIn where bDelete = 0 AND  iBoxId= '{$data[0]['iBoxId']}' ";
           $data = $this->db->fetchAll($sql);
           $arr['current'] = $data[0]['nums'];

           return $this->sendJsonResponse($arr);
       }catch (\Exception $e){
           return $this->sendErrorResponse(500,$e->getMessage());
       }
    }

    /**
     * 设备入库
     *
     * create by dale 20180239
     */
    public function devInFormAction(){
        $this->view->pick('res/devInForm');
        Assets::select2();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/res/devInForm.js');

    }

    /**
     * 获取单位
     *
     * @param $prodId
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by dale 20180239
     */
    public function getMeasureAction($prodId)
    {
        if(!$prodId){
            $prodId = $this->request->getPost('prodId');
        }
        $product = XHImsProduct::findFirst($prodId);
        $measures = $product->sMeasures;
        $measures = explode('/', $measures);
        $arr = [];
        foreach ($measures as $measure) {
            if($this->isSingle($measure)){
                $arr['single'] = $measure;
            }else{
                $arr['total']  = $measure;
            }
        }
        return $this->sendJsonResponse($arr);
    }

    /**
     * 获取默认的数目
     *
     * create by dale 20180239
     */
    public function getDefaultNumAction(){
        $prodId = $this->request->getPost('prodId','int');

        if(!$prodId){
            return $this->sendErrorResponse(400,'缺少参数');
        }
        $num = XHImsProduct::findFirst($prodId)->iDefNum;
        return $this->sendJsonResponse(['num' =>$num ]);
    }

    /**
     * 保存平板
     *
     * create by dale 20180239
     */
    public function saveInTabAction($scan=false){
        $post = $this->request->getPost();
        if ($scan) {
            if(!$post['code']){
                return $this->sendErrorResponse(400,'二维码必填');
            }

            if($post['sMeasure'] == 'single'){ //单个
                $obj = new XHImsProdIn();
                if ($this->checkPord($post['code'])) {
                    return $this->sendErrorResponse(500, '入库失败,物品码重复');
                }
                $obj->sProdCode = $post['code'];
            }else{ //多个
                $obj = new XHImsBoxIn();
                if ($this->checkBox($post['code'])) {
                    return $this->sendErrorResponse(500, '入库失败,物品码重复');
                }
                $defaultNum = XHImsProduct::findFirst($post['iProdId'])->iDefNum;
                $obj->iProdNum = $defaultNum;
                $obj->iLeftNum = $defaultNum;
                $obj->sBoxCode = $post['code'];
                $obj->iBoxNum  = 1;
            }
            $obj->iInPrice  = $post['iInPrice'];
            $obj->iTypeId = $post['iTypeId'];
            $obj->iProdId = $post['iProdId'];
            $res = $obj->save();
            if($res){
                if($post['sMeasure'] == 'single'){
                    $this->saveDevStore($post['code']);
                }
                return $this->sendJsonResponse(['code'=>200,'msg'=>'入库成功'],true);
            }
        }else{
            if($post['prodNum']< 0){
                return $this->sendErrorResponse(400,'数目不能少于0');
            }

            if($post['boxNum'] || $post['prodNum'] > 1 ){ //多数目入库
                $box = new XHImsBoxIn();
                $box->iTypeId = $post['iTypeId'];
                $box->iProdId = $post['iProdId'];
                $box->iBoxNum = isset($post['boxNum']) ? $post['boxNum'] : null;
                $box->iProdNum = $post['prodNum'];
                $box->iLeftNum = $post['prodNum'];
                $box->iInPrice  = $post['iInPrice'];
                if($box->save()){
                    return $this->sendJsonResponse(['code'=>200,'msg'=>'入库成功'],true);
                }
            }else{
                $prod = new XHImsProdIn();
                $prod->iTypeId   = $post['iTypeId'];
                $prod->iProdId   = $post['iProdId'];
                $prod->iInPrice  = $post['iInPrice'];
                if($prod->save()){
                    return $this->sendJsonResponse(['code'=>200,'msg'=>'入库成功'],true);
                }
            }
        }



    }


    /**
     * 检查箱码是否重复
     * @param $name
     * @return bool
     * created by dale 2017/9/14
     */
    public function checkBox($name)
    {
        $box = XHImsBoxIn::findFirst([
            'conditions' => 'bDelete=0 AND sBoxCode=:sBoxCode:',
            'bind' => ['sBoxCode' => $name]
        ]);
        if ($box) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查只吗是否重复
     * @param $name
     * @return bool
     * created by dale 2017/9/14
     */
    public function checkPord($name)
    {
        $prod = XHImsProdIn::findFirst([
            'conditions' => 'bDelete=0 AND sProdCode=:sProdCode:',
            'bind' => ['sProdCode' => $name]
        ]);
        if ($prod) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 保存到设备库
     *
     * @param $code
     * @return bool
     *
     * created by dale 2017/11/29
     */
    public function saveDevStore($code){
        $obj   = new XHsysDeviceStore();
        $check = XHsysDeviceStore::findFirst([
            'conditions' => 'bDelete = 0 AND sDeviceNumber = :sDeviceNumber:',
            'bind'       => ['sDeviceNumber'=>$code]
        ]);
        if($check){
            return false;
        }
        $obj->sDeviceNumber = $code;
        $res = $obj->save();
        return $res;
    }

    /**
     * 判断是否可入库
     *
     * @param $boxCode
     * @return bool
     *
     * create by dale 20171212
     */
    private function isCouldInBox($boxCode){
        $arr = [];
        $sql = "select iBoxId,iProdNum from XHIms_BoxIn where bDelete = 0 AND sBoxCode = '{$boxCode}' ";
        $data = $this->db->fetchOne($sql);
        $arr['total']   = $data['iProdNum'];
        $sql = "select count(iPInId) as nums from XHIms_ProdIn where bDelete = 0 AND  iBoxId= '{$data[0]['iBoxId']}' ";
        $data = $this->db->fetchOne($sql);
        $arr['current'] = $data['nums'];
        if(intval($arr['total'])-intval($arr['current']) == 0 ){
            return false;
        }else{
            return true;
        }
    }

    /**
     * 其他入库
     *
     * @param bool $scan
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180240
     */
    public function saveInOtherAction($scan=false){
        $post  = $this->request->getPost();
        try{
            if($scan){  //单个入库 箱或者个
                if(!$post['code']){
                    return $this->sendErrorResponse(400,'二维码必填');
                }
                if($post['sMeasure'] == 'single'){ //单个
                    $obj = new XHImsProdIn();
                }else{ //多个
                    $obj = new XHImsBoxIn();
                    $defaultNum = XHImsProduct::findFirst($post['iProdId'])->iDefNum;
                    $obj->iProdNum = $defaultNum;
                    $obj->iLeftNum = $defaultNum;
                    $obj->iBoxNum  = 1;
                }
                $obj->iInPrice  = $post['iInPrice'];
                $obj->iTypeId = $post['iTypeId'];
                $obj->iProdId = $post['iProdId'];
                if($obj->save()){
                    return $this->sendJsonResponse(['code'=>200,'msg'=>'入库成功'],true);
                }
                return $this->sendErrorResponse(500,'保存失败');
            }else{ //其他入库
                if($post['prodNum']< 0){
                    return $this->sendErrorResponse(400,'数目不能少于0');
                }
                if($post['boxNum'] || $post['prodNum'] > 1 ){ //多数目入库
                    $box = new XHImsBoxIn();
                    $box->iTypeId = $post['iTypeId'];
                    $box->iProdId = $post['iProdId'];
                    $box->iBoxNum = isset($post['boxNum']) ? $post['boxNum'] : null;
                    $box->iProdNum = $post['prodNum'];
                    $box->iLeftNum = $post['prodNum'];
                    $box->iInPrice  = $post['iInPrice'];
                    if($box->save()) {
                        return $this->sendJsonResponse(['code' => 200, 'msg' => '入库成功'], true);
                    }
                }else{
                    $prod = new XHImsProdIn();
                    $prod->iTypeId   = $post['iTypeId'];
                    $prod->iProdId   = $post['iProdId'];
                    $prod->iInPrice  = $post['iInPrice'];
                    if($prod->save()){
                        return $this->sendJsonResponse(['code'=>200,'msg'=>'入库成功'],true);
                    }
                }
                return $this->sendErrorResponse(500,'保存失败');
            }
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 扫码入库
     *
     * create by dale 20180240
     */
    public function scanInFormAction(){
        $this->view->pick('res/scanInForm');
        Assets::select2();
        Assets::importMainJs('assets/xh/xhForm.js');
        Assets::importJs('js/res/scanInForm.js');
    }

    /**
     * 修改价格
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180620
     */
    public function modifyPriceAction(){
        $id    = $this->request->getPost('id'    , 'int');
        $flag  = $this->request->getPost('flag'  , 'string');
        $price = $this->request->getPost('price' , 'int');
        $type  = $this->request->getPost('type'  , 'string');
        if (!$id || !$flag || !$price ) {
            return $this->sendErrorResponse(401 ,'缺少参数');
        }
        if ($type == 'in') {
            if ($flag == 'box') {
                $obj = XHImsBoxIn::findFirst($id);
                $obj->iInPrice = $price;
            } else if ($flag == 'prod') {
                $obj = XHImsProdIn::findFirst($id);
                $obj->iInPrice = $price;
            } else {
                return $this->sendErrorResponse(400 ,'未知商品类型');
            }
        } else if ($type == 'out') {
            if ($flag == 'box') {
                $obj = XHImsBoxOut::findFirst($id);
                $obj->iOutPrice = $price;
            } else if ($flag == 'prod') {
                $obj = XHImsBoxOut::findFirst($id);
                $obj->iOutPrice = $price;
            } else {
                return $this->sendErrorResponse(400 ,'未知商品类型');
            }
        } else {
            return $this->sendErrorResponse(500 , '未知类型');
        }
        if(!$obj->save()){
            return $this->sendErrorResponse(500 , '价格修改失败');
        }
        $this->praseLog('价格修改成功' , '价格修改成功');
        return $this->response->setJsonContent(['code' =>  200, 'msg' => '价格修改成功'], JSON_UNESCAPED_UNICODE);
    }

    /**
     * 计算价格
     *
     * @param $data
     * @param string $field
     * @param string $numField
     * @return float|int
     * create by xjq 20180622
     */
    public function calculatePrice($data , $field = 'iInPrice',$numField='iProdNum'){
        $total = 0;
        foreach ($data as $row ) {
            if(isset($row[$field])){
                $total += $row[$numField] * $row[$field];
            }
        }
        return $total;
    }

    /**
     * 保存出库
     *
     * create by xjq 20180622
     */
    public function saveOutResAction(){
        try{
            $postData = $this->request->getPost();
            $prodId = $this->request->getPost('iProdId','int');
            $prodType =$this->request->getPost('iTypeId' ,'int');
            $prodNum  = $this->request->getPost('iOutNum','int');
            if(!$prodId || !$prodType || !$prodNum){
                return $this->sendErrorResponse(500 , '缺少参数');
            }
            Ims::resOut($postData);
            $this->praseLog('出库' , '保存出库');
            return $this->response->setJsonContent(['code' =>  200, 'msg' => '出库成功'], JSON_UNESCAPED_UNICODE);
        }catch (XhException $e){
            return $this->sendErrorResponse(500 ,$e->getMessage() , $e->getDescription());
        }
    }


    /**
     * 保存出库
     *
     * create by xjq 20180622
     */
    public function saveInResAction(){
        try{
            $postData = $this->request->getPost();
            $prodId = $this->request->getPost('iProdId','int');
            $prodType =$this->request->getPost('iTypeId' ,'int');
            $prodNum  = $this->request->getPost('prodNum','int');
            if(!$prodId || !$prodType || !$prodNum){
                return $this->sendErrorResponse(500 , '缺少参数');
            }
            Ims::resIn($postData);
            $this->praseLog('出库' , '保存出库');
            return $this->response->setJsonContent(['code' =>  200, 'msg' => '出库成功'], JSON_UNESCAPED_UNICODE);
        }catch (XhException $e){
            return $this->sendErrorResponse(500 ,$e->getMessage() , $e->getDescription());
        }
    }

    /**
     * 保存备注
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180702
     */
    public function saveDescAction(){
        try{
            $id = $this->request->getPost('id' , 'string');
            $sRemark = $this->request->getPost('sRemark' , 'string');
            $flag = $this->request->getPost('flag' ,'string');
            $type = $this->request->getPost('type' , 'string');
            if($type == 'in'){ //入库
                if ($flag == 'box' ) {
                    $obj = XHImsBoxIn::findFirst($id);
                } else {
                    $obj = XHImsProdIn::findFirst($id);
                }
            }else{ //出库
                if ($flag == 'box') {
                    $obj = XHImsBoxOut::findFirst($id);
                }else{
                    return $this->sendErrorResponse(400 ,'该表不存在备注字段');
                }
            }
            if (!$obj) {
                return $this->sendErrorResponse(400 ,'缺少参数');
            }
            if($obj->sRemark){
                $obj->sRemark = substr($obj->sRemark , -1) == ';' ? $obj->sRemark  . $sRemark : $obj->sRemark . ';' . $sRemark;
            }else{
                $obj->sRemark = $sRemark;
            }
            if(!$obj->save()){
                return $this->sendErrorResponse(500 ,'保存失败');
            }
            $this->praseLog('备注保存成功', '备注保存成功');
            return $this->response->setJsonContent(['code' => 200, 'msg' => '备注保存成功'], JSON_UNESCAPED_UNICODE);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }



}